<template>
  <div class="operation-log-list">
    <a-form layout="inline" ref="formRefBase">
      <a-form-item label="">
        <a-select
          v-model="queryParam.modelType"
          placeholder="模型类型"
          default-value="0"
          :style="{
            width: '210px',
          }"
        >
          <a-select-option value="">全部</a-select-option>
          <a-select-option value="P">Python</a-select-option>
          <a-select-option value="J">PMML</a-select-option>
          <a-select-option value="GM">评分卡</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="">
        <a-input
          v-model="queryParam.modelName"
          placeholder="输入名称"
          :style="{
            width: '210px',
          }"
        />
      </a-form-item>
      <a-form-item label="">
        <a-badge :count="filterLength">
          <a-button icon="filter" style="margin-right: 12px" @click="drawerVisible = true">更多过滤</a-button>
        </a-badge>
        <a-button type="primary" @click="searchHandle">搜索</a-button>
      </a-form-item>
    </a-form>
    <s-table
      ref="table"
      size="default"
      rowKey="id"
      :columns="columns"
      :data="loadData"
      :alert="false"
      showPagination="auto"
      class="call-log-list-table"
    >
      <template slot="callNumber" slot-scope="text, record">
        <a-tooltip>
          <template slot="title">{{ record.callNumber }}</template>
          {{ record.callNumber }}
        </a-tooltip>
      </template>
      <template slot="modelName" slot-scope="text, record">
        <a-tooltip>
          <template slot="title">{{ record.modelName }}</template>
          {{ record.modelName }}
        </a-tooltip>
      </template>
      <template slot="success" slot-scope="text, record">
        <a-tag :color="record.success ? 'green' : 'red'">
          {{ record.success ? '成功' : '失败' }}
        </a-tag>
      </template>
      <span slot="operation" slot-scope="text, record">
        <a-button type="link" @click="handleDetail(record)" v-if="$hasPermission('callLogDetail')">详情</a-button>
      </span>
    </s-table>
    <a-modal title="详情" :visible="visible" @ok="visible = false" @cancel="visible = false" width="800px">
      <a-descriptions :column="1">
        <a-descriptions-item label="调用结果"> {{ detailData.success ? '成功' : '失败' }} </a-descriptions-item>
        <a-descriptions-item label="执行时间"> {{ detailData.timestamp | formatTime }} </a-descriptions-item>
        <a-descriptions-item label="模型UUID"> {{ detailData.modelUuid }} </a-descriptions-item>
        <a-descriptions-item label="模型版本"> {{ detailData.modelVersion }} </a-descriptions-item>
        <a-descriptions-item label="业务来源ID">
          {{ detailData.seqId }}
        </a-descriptions-item>
        <a-descriptions-item label="入参">
          <SearchTable :dataSource="processTableData(detailData.inputs)" />
        </a-descriptions-item>
        <a-descriptions-item label="出参">
          <SearchTable :dataSource="processTableData(detailData.data)" />
        </a-descriptions-item>
      </a-descriptions>
    </a-modal>
    <a-drawer
      title="模型调用搜索"
      :visible="drawerVisible"
      @close="onClose"
      width="400px"
      :getContainer="$drawerConfig.getContainer"
    >
      <a-form ref="formRef" layout="vertical" hide-required-mark>
        <a-form-item label="调用编号">
          <a-input v-model="queryParam.callNumber" placeholder="输入调用编号" />
        </a-form-item>
        <a-form-item label="业务来源ID">
          <a-input v-model="queryParam.seqId" placeholder="输入业务来源ID" />
        </a-form-item>
        <a-form-item label="模型编号">
          <a-input v-model="queryParam.modelUuid" placeholder="输入模型编号" />
        </a-form-item>
        <a-form-item label="模型版本">
          <a-input v-model="queryParam.modelVersion" placeholder="输入模型版本" />
        </a-form-item>
        <a-form-item label="选择时间">
          <a-range-picker
            :show-time="{ format: 'HH:mm:ss' }"
            format="YYYY-MM-DD HH:mm:ss"
            v-model="queryParam.timeRange"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </a-form-item>
        <a-button type="primary" @click="searchHandle" block style="margin-bottom: 12px">搜索</a-button>
        <a-button @click="resetHandle" block>清空</a-button>
      </a-form>
    </a-drawer>
  </div>
</template>

<script>
import { defineComponent } from 'vue'
import { STable, SearchTable } from '@/components'
import { getModelCallLogList, getModelCallLogDetail } from '@/api/modelLog'
import moment from 'moment'

const columns = [
  {
    title: '调用编号',
    dataIndex: 'callNumber',
    width: 240,
    ellipsis: true,
    scopedSlots: { customRender: 'callNumber' },
  },
  {
    title: 'SEQID',
    dataIndex: 'seqId',
    width: 240,
  },
  {
    title: '调用时间',
    dataIndex: 'timestamp',
    width: 180,
    customRender: (text, record) => {
      return moment(text).format('YYYY-MM-DD HH:mm:ss')
    },
  },
  {
    title: '模型编号',
    dataIndex: 'modelUuid',
    width: 180,
  },
  {
    title: '模型版本',
    dataIndex: 'modelVersion',
    width: 80,
  },
  {
    title: '模型名称',
    dataIndex: 'modelName',
    width: 180,
    scopedSlots: { customRender: 'modelName' },
  },
  {
    title: '模型类型',
    dataIndex: 'modelType',
    width: 80,
    customRender: (text, record) => {
      const typeMap = {
        P: 'Python',
        J: 'PMML',
        GM: '评分卡',
      }
      return typeMap[text] || ''
    },
  },
  {
    title: '调用结果',
    dataIndex: 'success',
    width: 120,
    fixed: 'right',
    scopedSlots: { customRender: 'success' },
  },
  {
    title: '操作内容',
    scopedSlots: { customRender: 'operation' },
    width: 100,
    dataIndex: 'operContent',
    fixed: 'right',
  },
]
export default defineComponent({
  name: 'CallLogList',
  components: {
    STable,
    SearchTable,
  },
  props: {},
  data() {
    return {
      columns,
      inputColumns: [
        {
          title: 'Key',
          dataIndex: 'name',
          key: 'name',
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'customRender',
          },
          onFilter: (value, record) => record.name.toString().toLowerCase().includes(value.toLowerCase()),
          onFilterDropdownVisibleChange: (visible) => {
            if (visible) {
              setTimeout(() => {
                this.searchInput.focus()
              }, 0)
            }
          },
        },
        {
          title: 'Value',
          dataIndex: 'value',
          key: 'value',
        },
      ],
      visible: false,
      queryParam: {
        callNumber: '',
        endTime: '',
        modelName: '',
        modelType: '',
        modelUuid: '',
        seqId: '',
        startTime: '',
        modelVersion: '',
        timeRange: null, // 添加这个字段
      },
      detailData: {},
      drawerVisible: false,
    }
  },
  filters: {
    formatTime(timestamp) {
      return moment(timestamp).format('YYYY-MM-DD HH:mm:ss')
    },
  },
  computed: {
    // 已选择的筛选项总数
    filterLength() {
      const { queryParam } = this
      const fields = ['modelType', 'modelName', 'callNumber', 'seqId', 'modelUuid', 'modelVersion']

      // 计算普通字段的数量
      let count = fields.reduce((sum, field) => {
        return sum + (queryParam[field] ? 1 : 0)
      }, 0)

      // 特殊处理 timeRange
      if (queryParam.timeRange) {
        count += queryParam.timeRange.length
      }

      return count
    },
  },
  created() {
    // 设置默认时间范围为今天往前七天
    const endDate = moment().endOf('day')
    const startDate = moment().subtract(7, 'days').startOf('day')
    this.$set(this.queryParam, 'timeRange', [
      startDate.format('YYYY-MM-DD HH:mm:ss'),
      endDate.format('YYYY-MM-DD HH:mm:ss'),
    ])
  },
  methods: {
    processTableData(data) {
      if (!data) {
        return []
      }
      return Object.entries(data).map(([key, value]) => ({
        name: key,
        value,
      }))
    },
    searchHandle() {
      this.$refs.table.refresh(true)
    },
    resetHandle() {
      this.queryParam = {}
      this.$refs.table.refresh(true)
      this.$refs.formRef.resetFields()
      this.$refs.formRefBase.resetFields()
    },
    loadData(parameter) {
      console.log('parameter:', parameter)
      const requestParameters = Object.assign(
        {},
        {
          curPage: parameter.pageNo,
          pageSize: parameter.pageSize,
        },
        this.queryParam
      )
      if (requestParameters.timeRange && requestParameters.timeRange.length) {
        // 转化为时间戳
        requestParameters.startTime = moment(requestParameters.timeRange[0]).unix() * 1000
        requestParameters.endTime = moment(requestParameters.timeRange[1]).unix() * 1000
        delete requestParameters.timeRange
      }
      console.log('loadData request parameters:', requestParameters)
      return getModelCallLogList(requestParameters).then((res) => {
        return res.data
      })
    },
    handleDetail(record) {
      getModelCallLogDetail({
        callNumber: record.callNumber,
        timestamp: record.timestamp,
      }).then((res) => {
        if (res.data) {
          this.visible = true
          this.detailData = res.data
          console.log('detailData:', this.detailData)
          return
        }
        this.$message.error(res.message)
      })
    },
    onClose() {
      this.drawerVisible = false
    },
  },
})
</script>

<style lang="less" scoped>
.call-log-list-table {
  margin-top: 16px;
}
</style>
